package com.example.iot.utils;

import android.app.DownloadManager;
import android.util.Log;

import androidx.annotation.NonNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MultipartBody;
import okhttp3.OkHttp;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpUtils {
    //get的异步请求
    public static void getSync(String uri, Callback callback,OkHttpClient okHttpClient){
                Request request=new Request.Builder().url(uri).build();
                Call call= okHttpClient.newCall(request);
                call.enqueue(callback);
    }

    //post的同步请求
    public static void postSync(String uri,String username,String password,Callback callback) {
        new Thread(){
            @Override
            public void run() {
                OkHttpClient okHttpClient=new OkHttpClient();
                FormBody formBody=new FormBody.Builder().add("username",username).add("password",password).build();
                Request request=new Request.Builder().url(uri).post(formBody).build();
                Call call=okHttpClient.newCall(request);
                try{
                    Response response = call.execute();
                    call.enqueue(callback);
                    Log.e("post同步请求","postSync:"+response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                super.run();
            }
        }.start();
    }

    //post异步请求
    public static void posyAsync(String url,String username,String password,Callback callback) {
        OkHttpClient okHttpClient=new OkHttpClient();
        RequestBody muiltipartBody = new MultipartBody.Builder()
                //一定要设置这句
                .setType(MultipartBody.FORM)
                .addFormDataPart("username", username)
                .addFormDataPart("password", password)
                .build();
        //FormBody formBody = new FormBody.Builder().add("username", "yt").add("password", "yt1234").build();
        // RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;charset=utf-8"), "select * from user");
        Request request = new Request.Builder().url(url)
                .post(muiltipartBody)
                .addHeader("token","test")
                .build();
        Call call=okHttpClient.newCall(request);
        call.enqueue(callback);
    }


}
